package cumeo89.chii.client.ui;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;

public class AnchorPositionCallback implements PositionCallback {

	private PopupPanel panel;
	private Element element;
	private Direction direction;

	public AnchorPositionCallback(PopupPanel panel, Widget widget,
			Direction direction) {
		this(panel, widget.getElement(), direction);
	}

	public AnchorPositionCallback(PopupPanel panel, Element element,
			Direction direction) {
		this.panel = panel;
		this.element = element;
		this.direction = direction;
	}

	public Element getElement() {
		return element;
	}

	public void setElement(Element element) {
		this.element = element;
	}

	public void setPosition(int offsetWidth, int offsetHeight) {
		int left, top;
		int ww = Window.getClientWidth(), wh = Window.getClientHeight();
		int ew = element.getPropertyInt("offsetWidth"), eh = element
				.getPropertyInt("offsetHeight");
		int et = element.getAbsoluteTop(), el = element.getAbsoluteLeft();
		switch (direction) {
		case HORIZONTAL:
			top = et;
			left = el + ew + 2;
			if (left + offsetWidth > ww && el >= offsetWidth + 2) {
				left = el - offsetWidth - 2;
			}
			break;
		case VERTICAL:
			left = el;
			top = et + eh + 2;
			if (top + offsetHeight > wh && et >= offsetHeight + 2) {
				top = et - offsetHeight - 2;
			}
			break;
		default:
			return;
		}
		// if (left + offsetWidth > ww && ww >= offsetWidth + 2) {
		// left = ww - offsetWidth - 2;
		// }
		// if (top + offsetHeight > wh && wh >= offsetHeight + 2) {
		// top = wh - offsetHeight - 2;
		// }
		panel.setPopupPosition(left, top);
	}

	public enum Direction {
		HORIZONTAL, VERTICAL
	}

}
